<template>
  <div class="innerPageTable-box-OneTwo value-set-list-wrap innerPageTable-out-flex">
    <!-- 搜索区域 -->
    <SelfAdaption style="margin:0px">
      <Form
        :model="searchForm"
        ref="serviceForm"
        slot="adaption-bar"
        label-position="top"
        class="ivu-form-no-margin-bottom"
        inline
      >
        <Form-item prop="todoType" :label="'表单名称：'">
          <Select filterable v-model="searchForm.todoType">
            <Option v-for="item in areaCodeList" :value="item.value" :key="item.key">{{ item.value }}</Option>
          </Select>
        </Form-item>
        <Form-item prop="trgNode" :label="'单位名称：'">
          <Select filterable clearable v-model="searchForm.trgNode" v-if="isNew">
            <Option v-for="item in filterOrgList" :value="item.orgCode" :key="item.orgCode">{{ item.orgName }}</Option>
          </Select>
          <Select filterable clearable v-model="searchForm.trgNode" v-else>
            <Option v-for="item in bussinessUnit" :value="item" :key="item">{{ item }}</Option>
          </Select>
        </Form-item>
        <Form-item prop="period" :label="'填报周期：'">
          <Select filterable v-model="searchForm.period">
            <Option v-for="item in periodList" :value="item.value" :key="item.value">{{ item.text }}</Option>
          </Select>
        </Form-item>
        <!-- 前端自定义即可：待审批、已审批 -->
        <Form-item prop="status" :label="'状态：'">
          <Select filterable v-model="searchForm.status">
            <Option v-for="item in statusList" :value="item" :key="item">{{ item }}</Option>
          </Select>
        </Form-item>
        <Form-item prop="wfTittle" :label="'标题：'">
          <Input
            type="text"
            v-model.trim="searchForm.wfTittle"
            :placeholder="'请输入'"
            @on-enter="searchValueSet"
          ></Input>
        </Form-item>
        <Form-item prop="approverName" :label="'审批人：'">
          <Input
            type="text"
            v-model.trim="searchForm.approverName"
            :placeholder="'请输入'"
            @on-enter="searchValueSet"
          ></Input>
        </Form-item>

        <!-- 查询\重置按钮 -->
        <Form-item prop="button" class="search-solt-btn">
          <RPButton optType="search" ref="search" @click="searchValueSet()" />
        </Form-item>
      </Form>
    </SelfAdaption>

    <InnerPageTable v-show="!isNew && unhandledSearch" ref="unhandledTable" :config="pageTableConfigUnhandled"> </InnerPageTable>
    <InnerPageTable v-show="!isNew && processedSearch" ref="processedTable" :config="pageTableConfigProcessed"> </InnerPageTable>
    <InnerPageTable v-show="isNew && unhandledSearch" ref="formCenterTableUnhandled" :config="pageTableConfigFormCenterUnhandled"></InnerPageTable>
    <InnerPageTable v-show="isNew && processedSearch" ref="formCenterTableProcessed" :config="pageTableConfigFormCenterProcessed"></InnerPageTable>
  </div>
</template>

<script>
import RateForm from '@/views/formCenter/writeForm/rateForm/index.vue'
import todoApi from '@/api/todoCender.js'
import coverApi from '@/api/cover.js'
import formCenterApi from '@/api/formCenter.js'
import { findObjectByValue } from '../utils/index'
import { mapState } from 'vuex'
import { columnListProcessed, columnListUnhandled, columnFormCenterUnhandled, columnFormCenterProcessed } from './columns'
export default {
  name: 'filling',
  mixins: [],
  props: {
    // areaCodeList: {
    //   type: Array,
    //   default: () => []
    // },
  },
  data() {
    return {
      isNew: false,
      newAreaCodeList: [],
      filterOrgList: [],
      unhandledSearch: false,
      processedSearch: false,
      areaCodeList: [],
      allPeriodList: [],
      bussinessUnit: [],
      periodList: [],
      statusList: ['待审批', '已审批'],
      searchForm: {
        todoType: '',
        trgNode: '',
        period: '',
        status: '待审批',
        statusCode: '',
        wfTittle: '',
        approverName: '',
        approverList: '',
        self: this
      },
      tableData: []
    }
  },
  computed: {
    ...mapState(['orgList', 'menuList']),
    pageTableConfigUnhandled() {
      return {
        loadDataFn: this.getApprovalList,
        columns: columnListUnhandled.bind(this)(this.searchForm.todoType),
        // columnsFn: this.columnListApproval,
        autoFirst: false //默认 就是 false, 要配置在这里
      }
    },
    pageTableConfigProcessed() {
      return {
        loadDataFn: this.getApprovalList,
        columns: columnListProcessed.bind(this)(this.searchForm.todoType),
        // columnsFn: this.columnListApproval,
        autoFirst: false //默认 就是 false, 要配置在这里
      }
    },
    pageTableConfigFormCenterUnhandled() {
      return {
        loadDataFn: this.getApprovalList,
        columns: columnFormCenterUnhandled.bind(this)(this.searchForm.todoType),
        autoFirst: false //默认 就是 false, 要配置在这里
      }
    },
    pageTableConfigFormCenterProcessed() {
      return {
        loadDataFn: this.getApprovalList,
        columns: columnFormCenterProcessed.bind(this)(this.searchForm.todoType),
        autoFirst: false //默认 就是 false, 要配置在这里
      }
    }
  },
  watch: {
    // orgList: {
    //   handler(val) {
    //     this.filterOrgList = val.filter(item => !item.children)
    //   }
    // },
    // 两个数组
    
    'searchForm.todoType': {
      async handler(val) {
        if (val) {
          const item = this.newAreaCodeList.find(item => item.value == val)
          if (item) {
            this.isNew = true
            //表单中心的数据--填报周期
            const res = await formCenterApi.formReportHistoryPeriod([item.key])
            this.periodList = []
            Array.from(new Set(res.data)).forEach(item => {
              this.periodList.push({ value: item, text: item })
            })
            this.searchForm.period = this.periodList[0]?.value
            this.searchForm.buname = ''
            // 获取单位名称
            const unitCodeList = await todoApi.getOrgList(item.bpmId)
            const result = unitCodeList.map(id => findObjectByValue(this.orgList, id)).filter(item => item!==null)
            this.filterOrgList = result
            this.searchForm.trgNode = this.filterOrgList[0]?.orgCode
          } else {
            this.isNew = false
            this.$set(this.searchForm, 'period', '')
            this.$set(this.searchForm, 'trgNode', '')
            this.getBussinessUnit()
            let areaCodeKey = this.areaCodeList.filter(item => item.value == val)[0]?.key
            let tempList = val ? this.allAreaList.filter(item => item.vsiKey == areaCodeKey) : []
            this.periodList = []
            try {
              this.periodList = tempList && tempList.length > 0 ? JSON.parse(tempList[0].vsiDescription) : []
              let defaultPeriod = this.periodList.filter(item => item.default == 'Y')[0]?.value
              this.$set(this.searchForm, 'period', defaultPeriod)
            } catch (error) {
              console.log(error)
            }
          }
          this.searchValueSet()
        }
      },
      immediate: true
    },
    'searchForm.approverName': {
      handler(val) {
        this.$set(this.searchForm, 'approverList', val)
      },
      immediate: true
    }
  },
  
  methods: {
    // init() {
    //   this.$nextTick(() => {
    //     this.searchValueSet()
    //   })
    // },
  
    // goProcessPage(bindId) {
    //   new this.$sidelipPage(
    //     RateForm,
    //     {
    //       props: {
    //         isDetail: true,
    //         row: {
    //           id: row.formId,
    //           recordId: row.recordId,
    //         }
    //       }
    //     }
    //   )
    //   // coverApi.getProcessUrl({ id: bindId, deviceType: 'PC' }).then(res => {
    //   //   window.open(res.data.data)
    //   // })
    // },
    getBussinessUnit() {
      if (this.searchForm.todoType) {
        let areacode = this.areaCodeList.filter(item => item.value == this.searchForm.todoType)[0].key
        todoApi.getBussinessUnit({ areaCode: areacode }).then(res => {
          if (res.data.code == 200) {
            this.bussinessUnit = res.data.data ? res.data.data.map(item => item.value) : []
          }
        })
      } else {
        this.bussinessUnit = []
      }
    },
    getApprovalList(tableObj) {
      let { responseProcess, param } = tableObj
      let { pageNum, pageSize, todoType, trgNode, period, status, wfTittle, approverName, approverList } = param
      if (this.newAreaCodeList.find(item => item.value == todoType)) {
        //表单数据
        formCenterApi
          .approvalPage({
            title: wfTittle,
            formId: this.newAreaCodeList.find(item => item.value == todoType)?.key,
            orgName: this.searchForm.trgNode,
            targetName: this.searchForm.approverName,
            approvalState: this.searchForm.status === '待审批' ? 0 : 1,
            period
          })
          .then(res => {
            let { current, size, records, pages, total } = res.data.data
            if (this.searchForm.status == '待审批') {
              this.unhandledSearch = true
              this.processedSearch = false
            } else if (this.searchForm.status == '已审批') {
              this.unhandledSearch = false
              this.processedSearch = true
            }
            responseProcess({
              pageNum: Number(current),
              size: Number(size),
              pages: pages,
              records: records || [],
              total: Number(total)
            })
            this.$nextTick(() => {
              // self.$refs['unhandledTable'].setTableScroll()
              this.$refs['processedTable'].setTableScroll()
            }, 1000)
          })
      } else {
        todoApi
          .getApprovalList({
            todoType,
            trgNode,
            period,
            status,
            wfTittle,
            approverName,
            approverList,
            currentPage: pageNum,
            pageNum,
            pageSize,
            sortOrderBy: 'DESC'
          })
          .then(res => {
            let { current, size, records, pages, total } = res.data.data
            if (this.searchForm.status == '待审批') {
              this.unhandledSearch = true
              this.processedSearch = false
            } else if (this.searchForm.status == '已审批') {
              this.unhandledSearch = false
              this.processedSearch = true
            }
            responseProcess({
              pageNum: Number(current),
              size: Number(size),
              pages: pages,
              records: records || [],
              total: Number(total)
            })
            this.$nextTick(() => {
              this.$refs['processedTable']?.setTableScroll()
            })
          })
      }
    },
    //搜索
    searchValueSet() {
      if (this.searchForm.status == '待审批' && !this.isNew) {
        this.$refs['unhandledTable'].load(this.searchForm)
      } else if (this.searchForm.status == '已审批' && !this.isNew) {
        this.$refs['processedTable'].load(this.searchForm)
      } else if (this.searchForm.status == '待审批' && this.isNew) {
        this.$refs['formCenterTableUnhandled'].load(this.searchForm)
      } else if (this.searchForm.status == '已审批' && this.isNew) {
        this.$refs['formCenterTableProcessed'].load(this.searchForm)
      }
    }
  },
  async created() {
    try {
      // 获取区域代码列表
      const areaCodeRes = await todoApi.getAreaCodeList()
      if (areaCodeRes.data.code === 200) {
        this.areaCodeList = areaCodeRes.data.data || []
      }

      // 获取新的区域代码列表（表单中心）
      const newAreaCodeRes = await formCenterApi.getNewAreaCodeList()
      if (newAreaCodeRes.data.code === 200) {
        this.newAreaCodeList = newAreaCodeRes.data.data.map(element => ({
          key: element.id,
          value: element.name,
          bpmId: element.bpmpId
        }))

        // 同时更新 areaCodeList
        this.areaCodeList.push(...newAreaCodeRes.data.data.map(element => ({
          key: element.id,
          value: element.name
        })))
      }
      // 获取所有区域列表
      const allAreaRes = await coverApi.getCodeList('AREA')
      this.allAreaList = allAreaRes.data.records || []

      // 查询完填报周期，设置领域默认值
      if (this.areaCodeList.length > 0) {
          this.$set(this.searchForm, 'todoType', this.areaCodeList[0].value)
      }

      // 初始化组织列表
      if (this.orgList.length <= 0) {
        await this.$store.dispatch('getOrgList')
      } else {
        this.filterOrgList = this.orgList.filter(item => !item.children);
      }

      // 初始化其他内容
      // this.init()
    } catch (error) {
      // 错误处理
      console.error('Failed to fetch data:', error);
      // 可以根据错误类型进行更具体的处理
    }
  },
}
</script>
<style lang="less" scoped>
/deep/.table-bar button:last-child {
  color: #ffffff;
  background-color: #ff6f4b;
  border-color: #ff6f4b;
}
.innerPageTable-box-OneTwo.value-set-list-wrap.innerPageTable-out-flex {
  height: calc(100% - 94px) !important;
}

/deep/ .self-adaption-wrap .self-adaption-flex {
  margin-bottom: 0px;
}
</style>

<style lang="less">
.icon-box {
  line-height: 30px;
  .ivu-icon {
    font-size: 28px;
  }
  .ivu-icon-ios-checkmark-circle {
    font-size: 28px;
    color: #19be6b;
  }
  .ivu-icon-ios-alert {
    font-size: 28px;
    color: #f90;
  }
  span {
    font-weight: bold;
    display: inline-block;
    vertical-align: top;
    margin-left: 5px;
  }
  p {
    margin-top: 10px;
    padding-left: 34px;
  }
  /deep/.ivu-btn-text {
    color: red;
    border: 1px solid transparent;
    // &:hover{
    //    border: 1px solid #ff6f4b
    // }
  }
}
</style>
